package com.example.service.impl;

import com.example.client.AccountClient;
import com.example.service.BusinessService;
import com.example.service.OrderService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
// TODO: 2021-11-2
@RequiredArgsConstructor
@Slf4j
public class BusinessServiceImpl implements BusinessService {

    private final OrderService orderService;

    @Autowired
    private  AccountClient accountClient;

    @Override
    @GlobalTransactional
    //todo 测试
    public void createAccountOrder(Integer accountId, Long amount, boolean hasException) {
        System.out.println("xid" + RootContext.getXID());


        //2.下订单
        orderService.createOrder(accountId,amount);


        //1.远程扣减账户余额
        String result = accountClient.debit(accountId,amount);
        log.info("远程扣减库存结果：[{}]",result);
        if (hasException){
            throw new RuntimeException("发生了异常，分布式事务需要回滚");
        }
    }
}
